<template>
  <div class="order-management">
    <el-card>
      <div slot="header" class="clearfix">
        <span class="page-title">订单管理</span>
        <div class="header-actions">
          <el-button
            class="export-btn"
            type="success"
            icon="el-icon-download"
            @click="handleExport">
            <span class="btn-text">导出订单</span>
          </el-button>
          <el-button
            class="refresh-btn"
            type="primary"
            icon="el-icon-refresh"
            @click="refreshData">
            <span class="btn-text">刷新数据</span>
          </el-button>
        </div>
      </div>

      <!-- 搜索表单 -->
      <div class="search-form">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="订单号">
            <el-input v-model="searchForm.tradeNo" placeholder="请输入订单号" clearable></el-input>
          </el-form-item>
          <el-form-item label="商家名称">
            <el-input v-model="searchForm.merchantName" placeholder="请输入商家名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="业务员">
            <el-input v-model="searchForm.salesmanName" placeholder="请输入业务员姓名" clearable></el-input>
          </el-form-item>
          <el-form-item label="订单状态">
            <el-select v-model="searchForm.statue" placeholder="请选择状态" clearable>
              <el-option label="待支付" :value="0"></el-option>
              <el-option label="已支付" :value="1"></el-option>
              <el-option label="已取消" :value="-1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="下单时间">
            <el-date-picker
              v-model="searchForm.startTime"
              type="date"
              placeholder="选择开始时间"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="至">
            <el-date-picker
              v-model="searchForm.endTime"
              type="date"
              placeholder="选择结束时间"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <configurable-table
        :columns="tableColumns"
        :data="tableData"
        :loading="loading"
        :show-pagination="true"
        :current-page.sync="pagination.current"
        :page-size.sync="pagination.size"
        :pagination-total="pagination.total"
        @page-change="loadData"
        border>
        <!-- 订单号列 -->
        <template #tradeNo="{ row }">
          <div class="order-info">
            <i class="el-icon-document"></i>
            <span class="order-no">{{ row.tradeNo }}</span>
          </div>
        </template>

        <!-- 商家名称列 -->
        <template #merchantName="{ row }">
          <div class="merchant-info">
            <i class="el-icon-shop"></i>
            <span>{{ row.merchantName }}</span>
          </div>
        </template>

        <!-- 业务员列 -->
        <template #salesmanName="{ row }">
          <div class="salesman-info">
            <i class="el-icon-user"></i>
            <span>{{ row.salesmanName || '业务员暂无名称' }}</span>
          </div>
        </template>

        <!-- 商品名称列 -->
        <template #productName="{ row }">
          <div class="product-info">
            <i class="el-icon-goods"></i>
            <span>{{ row.productName }}</span>
          </div>
        </template>

        <!-- 数量列 -->
        <template #num="{ row }">
          <el-tag size="small" type="info">{{ row.num }}</el-tag>
        </template>

        <!-- 佣金列 -->
        <template #commission="{ row }">
          <div class="commission-display">
            <span class="commission-value">¥{{ row.commission }}</span>
            <el-tag
              :type="getCommissionTag(row.commission)"
              size="mini"
              class="commission-tag">
              {{ getCommissionLevel(row.commission) }}
            </el-tag>
          </div>
        </template>

        <!-- 订单状态列 -->
        <template #statue="{ row }">
          <el-tag :type="getStatusTag(row.statue)">
            {{ getStatusText(row.statue) }}
          </el-tag>
        </template>

        <!-- 下单时间列 -->
        <template #createTime="{ row }">
          <div class="time-info">
            <i class="el-icon-time"></i>
            <span>{{ row.createTime }}</span>
          </div>
        </template>

        <!-- 操作列 -->
        <template #actions="{ row }">
          <el-button size="mini" icon="el-icon-view" @click="handleView(row)">查看</el-button>
          <el-button
            v-if="row.statue === 0"
            size="mini"
            type="warning"
            icon="el-icon-warning"
            @click="handleCancel(row)">
            取消
          </el-button>
        </template>
      </configurable-table>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      :visible.sync="detailDialogVisible"
      width="900px"
      custom-class="view-dialog"
      :close-on-click-modal="false">
      <div class="detail-content" v-if="detailData">
        <!-- 订单状态头部 -->
        <div class="detail-header">
          <el-tag :type="getStatusTag(detailData.statue)" size="small">
            {{ getStatusText(detailData.statue) }}
          </el-tag>
          <span class="order-no-text">{{ detailData.tradeNo || '无编号' }}</span>
        </div>

        <!-- 订单基本信息 -->
        <div class="info-section">
          <div class="section-title">
            <i class="el-icon-tickets"></i>
            <span>订单基本信息</span>
          </div>
          <el-row :gutter="20" class="info-row">
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-files"></i>
                  订单ID
                </div>
                <div class="info-value">{{ detailData.id || '无' }}</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-time"></i>
                  下单时间
                </div>
                <div class="info-value">{{ detailData.createTime || '无' }}</div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 商家信息 -->
        <div class="info-section">
          <div class="section-title">
            <i class="el-icon-shop"></i>
            <span>商家信息</span>
          </div>
          <el-row :gutter="20" class="info-row">
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-office-building"></i>
                  商家名称
                </div>
                <div class="info-value">{{ detailData.merchantName || '商家暂无名称' }}</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-user"></i>
                  业务员
                </div>
                <div class="info-value">{{ detailData.salesmanName || '业务员暂无名称' }}</div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 商品信息 -->
        <div class="info-section">
          <div class="section-title">
            <i class="el-icon-goods"></i>
            <span>商品信息</span>
          </div>
          <el-row :gutter="20" class="info-row">
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-box"></i>
                  商品名称
                </div>
                <div class="info-value">{{ detailData.productName || '无' }}</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-shopping-cart-full"></i>
                  商品数量
                </div>
                <div class="info-value">
                  <el-tag type="info" size="small">{{ detailData.num || 0 }} 件</el-tag>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-price-tag"></i>
                  单价
                </div>
                <div class="info-value">¥{{ detailData.unitPrice || 0 }}</div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 金额信息 -->
        <div class="info-section highlight-section">
          <div class="section-title">
            <i class="el-icon-wallet"></i>
            <span>金额信息</span>
          </div>
          <el-row :gutter="20" class="info-row">
            <el-col :span="12">
              <div class="info-item highlight-item">
                <div class="info-label">
                  <i class="el-icon-money"></i>
                  订单金额
                </div>
                <div class="info-value">
                  ¥{{ Number(detailData.amount || 0).toFixed(2) }}
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item highlight-item">
                <div class="info-label">
                  <i class="el-icon-coin"></i>
                  佣金金额
                </div>
                <div class="info-value">
                  ¥{{ Number(detailData.commission || 0).toFixed(2) }}
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-data-line"></i>
                  佣金比例
                </div>
                <div class="info-value">{{ detailData.commissionRate || 0 }}%</div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">
          <i class="el-icon-close"></i>
          关闭
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getOrderPage, getOrderList } from '@/api/aggregation'

export default {
  name: 'AgentOrderManagement',
  data() {
    return {
      loading: false,
      searchForm: {
        tradeNo: '',
        merchantName: '',
        salesmanName: '',
        statue: null,
        startTime: '',
        endTime: ''
      },
      tableData: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      // 表格列配置
      tableColumns: [
        { prop: 'id', label: '订单ID', minWidth: 120, align: 'center' },
        { prop: 'tradeNo', label: '订单号', minWidth: 200, slot: 'tradeNo' },
        { prop: 'merchantName', label: '商家名称', minWidth: 150, slot: 'merchantName' },
        { prop: 'salesmanName', label: '业务员', minWidth: 150, slot: 'salesmanName' },
        { prop: 'productName', label: '商品名称', minWidth: 200, showOverflowTooltip: true, slot: 'productName' },
        { prop: 'num', label: '数量', minWidth: 80, align: 'center', slot: 'num' },
        {
          prop: 'amount',
          label: '订单金额',
          minWidth: 120,
          sortable: true,
          formatter: (row) => `¥${row.amount}`
        },
        { prop: 'commission', label: '佣金', minWidth: 100, sortable: true, slot: 'commission' },
        { prop: 'statue', label: '订单状态', minWidth: 100, slot: 'statue' },
        { prop: 'createTime', label: '下单时间', minWidth: 180, sortable: true, slot: 'createTime' },
        { label: '操作', minWidth: 150, slot: 'actions' }
      ],
      // 详情对话框
      detailDialogVisible: false,
      detailData: null
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    // 加载数据
    async loadData() {
      this.loading = true
      try {
        const params = {
          pageIndex: this.pagination.current,
          pageSize: this.pagination.size
        }

        // 添加搜索条件
        if (this.searchForm.tradeNo) {
          params.tradeNo = this.searchForm.tradeNo
        }
        if (this.searchForm.merchantName) {
          params.merchantName = this.searchForm.merchantName
        }
        if (this.searchForm.salesmanName) {
          params.salesmanName = this.searchForm.salesmanName
        }
        if (this.searchForm.statue !== null && this.searchForm.statue !== '') {
          params.statue = this.searchForm.statue
        }
        if (this.searchForm.startTime) {
          params.startTime = this.searchForm.startTime
        }
        if (this.searchForm.endTime) {
          params.endTime = this.searchForm.endTime
        }

        const response = await getOrderPage(params)

        if (response.code === 0) {
          this.tableData = response.data.list || []
          this.pagination.total = response.data.total || 0
        } else {
          this.$message.error(response.msg || '加载订单数据失败')
          this.tableData = []
          this.pagination.total = 0
        }
      } catch (error) {
        console.error('加载订单数据失败:', error)
        this.$message.error('加载订单数据失败，请稍后重试')
        this.tableData = []
        this.pagination.total = 0
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1
      this.loadData()
    },

    // 重置
    handleReset() {
      this.searchForm = {
        tradeNo: '',
        merchantName: '',
        salesmanName: '',
        statue: null,
        startTime: '',
        endTime: ''
      }
      this.loadData()
    },

    // 刷新数据
    refreshData() {
      this.$message.success('数据已刷新')
      this.loadData()
    },

    // 查看详情
    handleView(row) {
      this.detailData = row
      this.detailDialogVisible = true
    },

    // 取消订单
    handleCancel(row) {
      this.$confirm('确定要取消该订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.success('订单已取消')
        this.loadData()
      })
    },

    // 导出订单
    async handleExport() {
      try {
        this.loading = true
        const params = {
          ...this.searchForm
        }

        const response = await getOrderList(params)

        if (response.code === 0) {
          const orders = response.data?.list || []

          if (orders.length === 0) {
            this.$message.warning('没有可导出的订单数据')
            return
          }

          // 使用全局方法：将表格列配置转换为导出列配置
          const exportColumns = this.$convertTableColumnsToExport(
            this.tableColumns,
            {
              // 为使用了 slot 的列提供格式化函数
              statue: (value) => this.getStatusText(value),
              tradeNo: (value) => value,
              merchantName: (value) => value,
              salesmanName: (value) => value,
              productName: (value) => value,
              num: (value) => value,
              commission: (value) => `¥${value}`,
              createTime: (value) => value
            },
            {
              // 排除操作列
              excludeProps: ['actions']
            }
          )

          // 使用全局方法：导出Excel文件
          this.$export(
            'excel',
            orders,
            exportColumns,
            `代理商订单数据_${new Date().toISOString().split('T')[0]}`,
            {
              sheetName: '订单数据',
              textColumns: [0, 1] // 将订单ID和订单号列设置为文本格式
            }
          )

          this.$message.success(`成功导出 ${orders.length} 条订单数据`)
        } else {
          this.$message.error('导出失败')
        }
      } catch (error) {
        console.error('导出订单失败:', error)
        this.$message.error('导出失败')
      } finally {
        this.loading = false
      }
    },

    // 获取状态标签类型
    getStatusTag(statue) {
      const statusMap = {
        0: 'warning',  // 待支付
        1: 'success',  // 已支付
        '-1': 'info'   // 已取消
      }
      return statusMap[statue] || 'info'
    },

    // 获取状态文本
    getStatusText(statue) {
      const statusMap = {
        0: '待支付',
        1: '已支付',
        '-1': '已取消'
      }
      return statusMap[statue] || '未知'
    },

    // 获取状态图标
    getStatusIcon(statue) {
      const iconMap = {
        0: 'el-icon-warning',  // 待支付
        1: 'el-icon-success',   // 已支付
        '-1': 'el-icon-remove' // 已取消
      }
      return iconMap[statue] || 'el-icon-info'
    },

    // 获取佣金标签类型
    getCommissionTag(commission) {
      if (commission >= 10) return 'success'
      if (commission >= 5) return 'warning'
      return 'info'
    },

    // 获取佣金等级
    getCommissionLevel(commission) {
      if (commission >= 10) return '高'
      if (commission >= 5) return '中'
      return '低'
    }
  }
}
</script>

<style scoped>
.order-management {
  padding: 20px;
}

.page-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.header-actions {
  float: right;
}

.export-btn {
  background: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
  border: none;
  border-radius: 8px;
  padding: 10px 20px;
  box-shadow: 0 4px 15px rgba(86, 171, 47, 0.3);
  transition: all 0.3s ease;
  margin-right: 10px;
}

.export-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(86, 171, 47, 0.4);
}

.refresh-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  padding: 10px 20px;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.refresh-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.order-info, .merchant-info, .salesman-info, .product-info, .time-info {
  display: flex;
  align-items: center;
}

.order-info i, .merchant-info i, .salesman-info i, .product-info i, .time-info i {
  margin-right: 5px;
  color: #409eff;
}

.order-no {
  font-weight: bold;
  color: #409eff;
}

.amount-display, .commission-display {
  display: flex;
  align-items: center;
  justify-content: space-evenly;
}

.amount-value, .commission-value {
  font-weight: bold;
  color: #303133;
}

.commission-tag {
  margin-left: 5px;
}

/* 订单详情弹框样式 */
.detail-content {
  padding: 0;
}

/* 详情头部 */
.detail-header {
  background: #f5f7fa;
  padding: 15px 20px;
  border-radius: 6px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-left: 3px solid #409eff;
}

.order-no-text {
  color: #606266;
  font-size: 14px;
}

/* 信息分组 - 使用全局样式，仅做少量定制 */
.info-item {
  /* 调整布局，使用横向布局而非全局的纵向布局 */
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-label {
  display: flex;
  align-items: center;
  min-width: 100px;
  margin-bottom: 0;
}

.info-value {
  text-align: right;
  flex: 1;
}

.highlight-item .info-value {
  color: #67c23a;
  font-weight: 600;
  font-size: 18px;
}

/* 对话框底部 */
.dialog-footer {
  text-align: center;
}

.dialog-footer .el-button {
  padding: 10px 30px;
  font-size: 14px;
  border-radius: 6px;
}
</style>
